package com.sskj.jkzx.repository.amap.message;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.sskj.jkzx.domain.entity.amap.message.Message;
import com.sskj.jkzx.domain.entity.amap.message.MessageQuery;

@Service
public class MessageQueryServiceImpl implements GernericQueryService {

	protected final Log logger = LogFactory.getLog(MessageQueryServiceImpl.class);

	public final static SimpleDateFormat DATA_FORMAT_YYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");

	public final static SimpleDateFormat DATA_FORMAT_YYYYMMDDHHMMSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Autowired
	MessageRepository messageRepository;

	@Transactional
	public void saveMessage(Message entity) {
		messageRepository.save(entity);
	}

	public List<Message> findAllOrderByCreatedTime() {
		return messageRepository.findAllOrderByCreatedTime();
	}

	/***
	 * 全部历史消息记录查询(分页，无查询条件)
	 * 
	 * @return
	 */
	@Override
	public Page<Message> findAllMessageNoCriteria(Integer page, Integer size) {
		Pageable pageable = new PageRequest(page, size, Sort.Direction.DESC, "createdTime");
		return messageRepository.findAll(pageable);
	}

	/***
	 * 获取当天记录数量
	 * 
	 * @param type
	 * @return
	 */
	public long findTodayCountByType(String type, Integer day) {
		return messageRepository.findTodayCountByType(type, day);
	}

	/***
	 * 全部历史消息记录查询(分页，有查询条件)
	 * 
	 * @return
	 */
	public Page<Message> findMessageCriteria(Integer page, Integer size, MessageQuery messageQuery) {
		Pageable pageable = new PageRequest(page, size, Sort.Direction.DESC, "createdTime");
		Page<Message> messagePage = messageRepository.findAll(new Specification<Message>() {
			@Override
			public Predicate toPredicate(Root<Message> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> list = new ArrayList<Predicate>();
				if (StringUtils.isNotEmpty(messageQuery.getType())) {
					list.add(criteriaBuilder.equal(root.get("type").as(String.class), messageQuery.getType()));
				}
				if (StringUtils.isNotEmpty(messageQuery.getContent())) {
					list.add(criteriaBuilder.like(root.get("content").as(String.class),
							"%" + messageQuery.getContent() + "%"));
				}
				if (StringUtils.isNotEmpty(messageQuery.getTime())) {
					try {
						String time = messageQuery.getTime();
						Date startTime = DATA_FORMAT_YYYYMMDD.parse(time);
						Calendar calendar = Calendar.getInstance();
						calendar.setTime(startTime);
						calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
						Date endTime = calendar.getTime();
						list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createdTime").as(String.class),
								DATA_FORMAT_YYYYMMDDHHMMSS.format(startTime)));
						list.add(criteriaBuilder.lessThan(root.get("createdTime").as(String.class),
								DATA_FORMAT_YYYYMMDDHHMMSS.format(endTime)));
					} catch (ParseException e) {
						logger.info("日期格式错误(yyyy-MM-dd)。" + messageQuery.getTime());
					}
				}
				Predicate[] p = new Predicate[list.size()];
				return criteriaBuilder.and(list.toArray(p));
			}
		}, pageable);
		return messagePage;
	}
}
